package com.project.myxima.presenters;

import android.widget.Toast;

import com.project.myxima.data.XimalayaApi;
import com.project.myxima.base.BaseApplication;
import com.project.myxima.interfaces.IPlayerCallback;
import com.project.myxima.interfaces.IPlayerPresenter;
import com.project.myxima.utils.Constants;
import com.project.myxima.utils.LogUtils;
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack;
import com.ximalaya.ting.android.opensdk.model.PlayableModel;
import com.ximalaya.ting.android.opensdk.model.advertis.Advertis;
import com.ximalaya.ting.android.opensdk.model.advertis.AdvertisList;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.model.track.TrackList;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.advertis.IXmAdsStatusListener;
import com.ximalaya.ting.android.opensdk.player.constants.PlayerConstants;
import com.ximalaya.ting.android.opensdk.player.service.IXmPlayerStatusListener;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayerException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PlayerPresenter implements IPlayerPresenter , IXmAdsStatusListener , IXmPlayerStatusListener {

    private static final int DEFAULT_PLAY_INDEX = 0;
    private List<IPlayerCallback> mIPlayerCallbacks = new ArrayList<>();

    private static final String TAG = "PlayerPresenter";
    private XmPlayerManager  mPlayerManager;
    private Track mCurrentTrack;
    private int mCurrentIndex = DEFAULT_PLAY_INDEX;
    /*private final SharedPreferences mPlayModSp;*/

    public boolean isPlayListSet = false;
    private int mCurrentProgress = 0;
    private int mCurrentDuration = 0;


    //单例化
    private PlayerPresenter(){
        //拿到播放器实例
        mPlayerManager = XmPlayerManager.getInstance(BaseApplication.getAppContext());
        //广告相关的接口
        mPlayerManager.addAdsStatusListener(this);
        //注册播放器相关的接口
        mPlayerManager.addPlayerStatusListener(this);

        //将当前的播放模式存储起来
        //mPlayModSp = BaseApplication.getAppContext().getSharedPreferences("PlayMod", Context.MODE_PRIVATE);
    }
    private static PlayerPresenter sPlayerPresenter;
    public static PlayerPresenter getPlayerPresenter(){
        if (sPlayerPresenter == null) {
            synchronized (PlayerPresenter.class){
                if (sPlayerPresenter == null) {
                    sPlayerPresenter = new PlayerPresenter();
                }
            }
        }
        return sPlayerPresenter;
    }


    public void setPlayList(List<Track> list, int playIndex){
        if (mPlayerManager != null) {
            mPlayerManager.setPlayList(list,playIndex);
            isPlayListSet = true;
            //获取一条track
            mCurrentTrack = list.get(playIndex);
            mCurrentIndex = playIndex;
        }else {
            LogUtils.d(TAG,"mPlayerManager为空");
        }
    }


    @Override
    public void play() {
        if(isPlayListSet){
            mPlayerManager.play();
        }
    }

    @Override
    public void pause() {
        if(isPlayListSet){
            mPlayerManager.pause();
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public void playNext() {
        if(isPlayListSet){
            mPlayerManager.playNext();
        }
    }

    @Override
    public void playPre() {
        if(isPlayListSet){
            //TODO:边界问题
            mPlayerManager.playPre();
        }
    }


    @Override
    public void seekTo(int progress) {
        //更新播放器进度
        mPlayerManager.seekTo(progress);

    }

    @Override
    public void reversePlayList() {
        List<Track> playList = mPlayerManager.getPlayList();
        Collections.reverse(playList);

        //update mCurrentIndex
        mCurrentIndex = playList.size() - 1 - mCurrentIndex;
        mPlayerManager.setPlayList(playList,mCurrentIndex);

        //update UI
        mCurrentTrack = (Track) mPlayerManager.getCurrSound();
        for(IPlayerCallback callback : mIPlayerCallbacks){
            callback.onListLoaded(playList);
            callback.onTrackUpdate(mCurrentTrack,mCurrentIndex);
        }
    }

    @Override
    public boolean hasPlayList() {
        return isPlayListSet;
    }

    @Override
    public void playByAlbumID(long albumID) {
        //1. get the content of track list
        XimalayaApi ximalayaApi = XimalayaApi.getXimalayaApi();
        ximalayaApi.getAlbumDetail(new IDataCallBack<TrackList>() {
            @Override
            public void onSuccess(TrackList trackList) {
                //2  set the content to the player
                List<Track> tracks = trackList.getTracks();
                if(trackList != null && tracks.size() >0){
                    mPlayerManager.setPlayList(tracks,0);
                    isPlayListSet = true;
                    //获取一条track
                    mCurrentTrack = tracks.get(DEFAULT_PLAY_INDEX);
                    mCurrentIndex = DEFAULT_PLAY_INDEX;
                }
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(BaseApplication.getAppContext(), "request fail",Toast.LENGTH_SHORT).show();
            }
        }, (int)albumID, 1);


    }

    @Override
    public void switchPlayMode(XmPlayListControl.PlayMode playMode) {
        if (mPlayerManager != null) {
            Constants.CURRENT_MODE = playMode;
            mPlayerManager.setPlayMode(Constants.CURRENT_MODE);
            for(IPlayerCallback iPlayerCallback:mIPlayerCallbacks){
                iPlayerCallback.onPlayModeChange(playMode);
            }
            //save play mode here
            /*SharedPreferences.Editor edit = mPlayModSp.edit();
            edit.putBool*/
        }
    }

    @Override
    public void getPlayList() {
        if (mPlayerManager != null) {
            List<Track> playList = mPlayerManager.getPlayList();
            for(IPlayerCallback iPlayerCallback:mIPlayerCallbacks){
                iPlayerCallback.onListLoaded(playList);
            }
        }
    }

    @Override
    public void playByIndex(int index) {
        if (mPlayerManager != null) {
            mPlayerManager.play(index);
        }
    }

    @Override
    public void registerViewCallback(IPlayerCallback iPlayerCallback) {
        handlePlayState(iPlayerCallback);
        iPlayerCallback.onProgressChange(mCurrentProgress,mCurrentDuration);
        iPlayerCallback.onTrackUpdate(mCurrentTrack,mCurrentIndex);
        iPlayerCallback.onPlayModeChange(Constants.CURRENT_MODE);//playmode here
        LogUtils.d(TAG, "-->registerViewCallback wymann");
        if (!mIPlayerCallbacks.contains(iPlayerCallback)) {
            mIPlayerCallbacks.add(iPlayerCallback);
        }
    }

    private void handlePlayState(IPlayerCallback iPlayerCallback) {
        int playerStatus = mPlayerManager.getPlayerStatus();

        if(PlayerConstants.STATE_STARTED == playerStatus){
            iPlayerCallback.onPlayStart();
        }else{
            iPlayerCallback.onPlayPause();
        }
    }

    @Override
    public void unregisterViewCallback(IPlayerCallback iPlayerCallback) {
        if(mIPlayerCallbacks.contains(iPlayerCallback)){
            mIPlayerCallbacks.remove(iPlayerCallback);
        }
    }

    /************************************** 广告相关的回调接口  start***************/

    @Override
    public void onStartGetAdsInfo() {
        LogUtils.d(TAG,"onStartGetAdsInfo...");

    }

    @Override
    public void onGetAdsInfo(AdvertisList advertisList) {
        LogUtils.d(TAG,"onGetAdsInfo...");

    }

    @Override
    public void onAdsStartBuffering() {
        LogUtils.d(TAG,"onAdsStartBuffering...");

    }

    @Override
    public void onAdsStopBuffering() {
        LogUtils.d(TAG,"onAdsStopBuffering...");

    }

    @Override
    public void onStartPlayAds(Advertis advertis, int i) {
        LogUtils.d(TAG,"onStartPlayAds...");

    }

    @Override
    public void onCompletePlayAds() {
        LogUtils.d(TAG,"onCompletePlayAds...");

    }

    @Override
    public void onError(int what, int extra) {
        LogUtils.d(TAG,"onError what -> " + what + "extra => " +  extra);

    }
    /************************************** 广告相关的回调接口  end ***************/


    /************************************** 播放器相关的回调接口  start ***************/
    @Override
    public void onPlayStart() {
        LogUtils.d(TAG,"onPlayStart");
        for(IPlayerCallback callback:mIPlayerCallbacks){
            callback.onPlayStart();
        }
    }

    @Override
    public void onPlayPause() {
        LogUtils.d(TAG,"onPlayPause");
        for(IPlayerCallback callback:mIPlayerCallbacks){
            callback.onPlayPause();
        }
    }

    @Override
    public void onPlayStop() {
        LogUtils.d(TAG,"onPlayStop");
        for(IPlayerCallback callback:mIPlayerCallbacks){
            callback.onPlayStop();
        }

    }

    @Override
    public void onSoundPlayComplete() {
        LogUtils.d(TAG,"onSoundPlayComplete");

    }

    @Override
    public void onSoundPrepared() {
        //当播放状态为已准备时，再开始播放
        if (mPlayerManager.getPlayerStatus() == PlayerConstants.STATE_PREPARED) {
            mPlayerManager.play();
        }
        LogUtils.d(TAG,"onSoundPrepared");

    }

    @Override
    public void onSoundSwitch(PlayableModel lastModel, PlayableModel curModel){
        LogUtils.d(TAG,"onSoundSwitch");
        mCurrentIndex = mPlayerManager.getCurrentIndex();
        //获取到curModel，如果它是Track，就提取它的名字
        if(curModel instanceof Track){
            mCurrentTrack = (Track) curModel;
            HistoryPresenter.getInstance().addHistory(mCurrentTrack);
            //更新UI
            for(IPlayerCallback iPlayerCallback:mIPlayerCallbacks){
                iPlayerCallback.onTrackUpdate(mCurrentTrack,mCurrentIndex);
            }
        }


    }

    @Override
    public void onBufferingStart() {
        LogUtils.d(TAG,"onBufferingStart");

    }

    @Override
    public void onBufferingStop() {
        LogUtils.d(TAG,"onBufferingStop");

    }

    @Override
    public void onBufferProgress(int progress) {
        LogUtils.d(TAG,"onBufferProgress  -->" + progress);

    }

    @Override
    public void onPlayProgress(int currentPos, int duration) {
        this.mCurrentDuration = duration;
        this.mCurrentProgress = currentPos;
        //单位为毫秒
        for(IPlayerCallback callback:mIPlayerCallbacks){
            callback.onProgressChange(currentPos,duration);
        }
        LogUtils.d(TAG,"onPlayProgress");

    }

    @Override
    public boolean onError(XmPlayerException e) {
        LogUtils.d(TAG,"onError e --> " + e );
        return false;
    }


    /************************************** 播放器相关的回调接口  end  ***************/

    @Override
    public boolean isPlaying() {
        return mPlayerManager.isPlaying();
    }


}
